package com.uh.microservice.core.spring.jdbc.adapter;

import com.github.yitter.idgen.YitIdHelper;
import com.uh.microservice.core.CONSTANTS;
import com.uh.microservice.core.spring.jdbc.JdbcAdapter;
import com.uh.microservice.core.spring.mvc.ThreadVariable;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class MssqlAdapter  extends JdbcAdapter {
    /**
     *  获取数据库表结构语句的具体实现方法，包括名称、中文名、数据类型等
     */
    @Override
    public String getSql4Tbl() {
        String sql="SELECT c.name, et.value AS text, tp.name AS type FROM sys.tables t , sys.schemas s, sys.columns c LEFT JOIN sys.extended_properties et ON c.object_id=et.major_id AND c.column_id=et.minor_id , sys.types tp WHERE s.name= :schema AND  t.name= :tname AND  t.schema_id=s.schema_id AND t.object_Id=c.object_Id AND c.system_type_id=tp.system_type_id ORDER BY c.column_id";
        return sql;
    }

    /**
     *  获取数据库表结构主键语句的实现方法
     */
    @Override
    public String getSql4TbPK(){
        // return "SELECT column_name as 'name' FROM information_schema.key_column_usage WHERE table_name = :tname and table_schema = :shcema ";
        return "SELECT COLUMN_NAME as 'name' FROM information_schema.key_column_usage WHERE table_name = :tname and table_schema = :shcema ";
    }

    /**
     *  合并分页语句与参数的实现方法
     */
    @Override
    public Map convertPageParam(Map param, Map pg) {
        Number start=(Number)pg.get("start");
        Number limit=(Number)pg.get("limit");
        param.put("start", start.intValue());
        param.put("end", limit.intValue());
        return param;
    }

    public Long crtKey(){
        Long id= YitIdHelper.nextId();
        return id;
        //return UUID.randomUUID().toString();
    }

    protected Map doInsertPre(Map entity){
        //entity.put("DjLsh",12322);
        entity.put("DjBth",2);
        entity.put("DjGuid", UUID.randomUUID().toString());
        return entity;
    }

    protected Map doAddEntity(String tbl, String sql, MapSqlParameterSource ps, Map entity){
        KeyHolder keyholder = new GeneratedKeyHolder();
        getTemplate().update(sql, ps, keyholder);
        int pk=keyholder.getKey().intValue();
        entity.put("DjLsh",pk);
        return entity;
    }

}
